﻿using Autofac;
using log4net;
using Microsoft.Extensions.DependencyModel;
using StudyCompanion.Core.Repository;
using StudyCompanion.Core.Services;
using StudyCompanion.Core.Share;
using System.Reflection;
using System.Runtime.Loader;

namespace StudyCompanion.Core.Extensions;

public class AutofacModuleRegister : Autofac.Module
{
    private static readonly ILog log = LogManager.GetLogger(typeof(AutofacModuleRegister));

    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterGeneric(typeof(BaseRepository<>)).InstancePerLifetimeScope();
        builder.RegisterType<UserContext>().As<IUserContext>().InstancePerLifetimeScope();

        List<Assembly> assemblyList = new();
        var libs = DependencyContext.Default.CompileLibraries.Where(lib =>
            lib.Type == "project" || lib.Name.EndsWith(".Services"));
        foreach (var lib in libs)
            assemblyList.Add(AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name)));

        foreach (var item in assemblyList)
        {
            var assembly = item;
            builder.RegisterAssemblyTypes(assembly)
                .Where(t => t.IsAssignableTo<IAppService>() && !t.IsAbstract)
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope();
        }

        builder.RegisterType<UserContext>().As<IUserContext>().InstancePerLifetimeScope();
    }
}